package com.llyb.chap04;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;

public class NotSafeDemo {

    public static void main(String[] args) throws InterruptedException {
        int ThreadNum = 10000;
        CountDownLatch countDownLatch = new CountDownLatch(ThreadNum);
        long start = System.currentTimeMillis();
        safeMap(ThreadNum, countDownLatch);

        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end-start));
    }


    private static void safeMap(int ThreadNum, CountDownLatch countDownLatch) {

        ConcurrentHashMap map = new ConcurrentHashMap<>();
        for (int i = 0; i < ThreadNum; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    map.put(finalI,UUID.randomUUID().toString().substring(0,8));
                    System.out.println(map);
                } finally {
                    countDownLatch.countDown();
                }
            },"T "+i).start();

        }
    }
    private static void safeArraySet(int ThreadNum, CountDownLatch countDownLatch) {
        CopyOnWriteArraySet set = new CopyOnWriteArraySet<>(); // 速度较慢
//        Set set = Collections.synchronizedSet(new HashSet<>());
        for (int i = 0; i < ThreadNum; i++) {
            new Thread(()->{
                try {
                    set.add(UUID.randomUUID().toString().substring(0,8));
                    System.out.println(set);
                } finally {
                    countDownLatch.countDown();
                }
            },"T "+i).start();

        }
    }
    private static void safeArrayList(int ThreadNum, CountDownLatch countDownLatch) {
        //        List list = new CopyOnWriteArrayList<>();
        List list = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < ThreadNum; i++) {
            new Thread(()->{
                try {
                    list.add(UUID.randomUUID().toString().substring(0,8));
                    System.out.println(list);
                } finally {
                    countDownLatch.countDown();
                }
            },"T "+i).start();

        }
    }
}
